package com.jfinal.dingtalk.api;

import com.jfinal.dingtalk.utils.JsonUtils;

import java.io.Serializable;
import java.util.Map;

/**
 * Created by L.cm on 2016/6/8.
 */
public class AccessToken implements Serializable {
    private static final long serialVersionUID = 8623283712613173596L;

    private Integer errCode;
    private String errMsg;
    private String accessToken;
    private String json;
    private long expiredTime;

    public AccessToken(String jsonStr) {
        this.json = jsonStr;
        try {
            Map<String, Object> map = JsonUtils.parse(jsonStr, Map.class);
            errCode = (Integer) map.get("errcode");
            errMsg  = (String) map.get("errmsg");
            accessToken = (String) map.get("access_token");
            expiredTime = System.currentTimeMillis() + ((7200 - 5) * 1000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Integer getErrcode() {
        return errCode;
    }

    public String getErrmsg() {
        return errMsg;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public String getJson() {
        return json;
    }

    public long getExpiredTime() {
        return expiredTime;
    }

    public boolean isAvailable() {
        if (errCode != null && errCode != 0)
            return false;
        if (expiredTime < System.currentTimeMillis())
            return false;
        return accessToken != null;
    }
}
